import axios from 'axios'
import { userStore } from '@/stores/user.ts'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

function refreshToken() {
  const user = userStore()
  return service.post('/refreshToken?refreshToken=' + user.token)
}

// 是否正在刷新的标记
let isRefreshing = false
// 重试队列，每一项将是一个待执行的函数形式
let requestsList : Array<any> = []

const service = axios.create({
  baseURL: '/app',
  timeout: 500000
})

service.interceptors.request.use((config: any) => {
  const user = userStore()
  const token = user.token
  if (token) {
    //  todo zpd token
    // config.headers.Authorization = 'Bearer ' + token
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 后置拦截
service.interceptors.response.use(
  response => {
    // 业务失败，消息提示
    const { code, msg } = response.data
    if (code === 200) {
      return response.data
    } else {
      ElMessage.error(msg)
      return Promise.reject(new Error(msg))
    }
  },
  async error => {
    const response = error.response
    const user = userStore()
    const router = useRouter()
    if (response.status === 401) {
      const config = error.config
      if (!isRefreshing) {
        isRefreshing = true
        try {
          try {
            const res = await refreshToken()
            const accessToken = res.data
            user.setToken(accessToken)
            requestsList.forEach((cb: (arg0: string) => void) => cb(accessToken))
            requestsList = []
            config.headers.Authorization = accessToken
            return await service(config)
          } catch (res_1) {
            console.error('refreshtoken error =>', res_1)
          }
        } finally {
          isRefreshing = false
        }
      } else {
        // 正在刷新token，将返回一个未执行resolve的promise
        return new Promise((resolve) => {
          // 将resolve放进队列，用一个函数形式来保存，等token刷新后直接执行
          requestsList.push((accessToken: string) => {
            config.headers.Authorization = accessToken
            resolve(service(config))
          })
        })
      }
    } else if (response.status === 402) {
      user.logout()
      await router.push({ name: 'login' })
      return Promise.reject(error)
    } else if (response.status === 400) {
      const msgList = response.data.data
      const str = msgList.join(';')
      ElMessage.error(str)
      return Promise.reject(error)
    } else {
      ElMessage.error(response.data.msg || '服务器连接异常')
      return Promise.reject(error)
    }
  }
)

export default service
